using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Timeline;
using UnityEngine.UI;
using UnityEngine.UIElements;

public class UpgradeBlink:Upgrade {

	protected override void SubscribeEvents() {
		base.SubscribeEvents();
		ActionSkillSlot.SkillTryOverride+=ActionSkillSlot_SkillOverride;
	}
	public override void UnsubscribeEvents() {
		base.UnsubscribeEvents();
		if(particle) {
			particle.SetActive(false);
			particle=null;
		}
		ActionSkillSlot.SkillTryOverride-=ActionSkillSlot_SkillOverride;
	}
	public override void OnDisable() {
		base.OnDisable();
		if(particle) {
			particle.SetActive(false);
			particle=null;
		}
	}

	private void ActionSkillSlot_SkillOverride(object sender) {
		ActionSkillSlot skill = sender as ActionSkillSlot;
		if(skill.mob!=weapon.owner) return;
		if(!canUse) return;
		if(!weapon.isActiveAndEnabled) return;
		if(skill.doOverride) return;
		skill.doOverride=true;

		weapon.owner.energy-=1;

		Vector2 teleportVector = weapon.owner.targetPosition-weapon.owner.position;
		if(teleportVector.magnitude>5) teleportVector=teleportVector.normalized*5;

		var hit = Physics2D.Raycast(weapon.owner.position,teleportVector,teleportVector.magnitude,Utility._losLayerMask,float.MinValue,float.MaxValue);
		if(hit) {
			teleportVector=hit.point-weapon.owner.position;
		}
		weapon.owner.transform.position+=(Vector3)teleportVector;
		timeSinceUse=0;
	}

	float timeSinceUse;
	const float cooldownTime = 5f;
	bool canUse;
	GameObject particle;

	public override void Update(object sender,WeaponEventArgs e) {
		base.Update(sender,e);

		timeSinceUse+=deltaTime;
		canUse=true;
		if(timeSinceUse<cooldownTime) canUse=false;
		if(weapon.owner.energy<1) canUse=false;

		if(canUse&&!particle) {
			particle=ParticleManager.Create("TeleportReady",weapon.owner.position);
		}
		if(particle) particle.transform.position=weapon.owner.position;
		if(!canUse&&particle) {
			particle.SetActive(false);
			particle=null;
		}
		AddProgression(timeSinceUse/cooldownTime);

	}

}
